package com.example.zhongshuishi.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.naming.NamingEnumeration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtTokenUtil {

    Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 根据用户信息生成token
     */
    public String generateToken(String id,String name,String phone,String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        claims.put("role", role);
        claims.put("sub", phone);
        claims.put("name",name);
        claims.put("exp", System.currentTimeMillis() + expiration);
        return generateToken(claims);
    }

    /**
     * 根据用户名、创建时间生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取登录用户手机号
     */
    public String getPhoneFromToken(String token) {
        String phoneJwt = null;
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            phoneJwt = claims.getSubject();
        }

        return phoneJwt;
    }
    /**
     * 从token中获取登录角色
     */
    public String getRoleFromToken(String token) {
        String role = null;
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            role = claims.get("role", String.class);
        }
        return role;
    }
    /**
     * 从token中获取登录角色id
     */
    public String getIdFromToken(String token) {
        String id = null;
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            id = claims.get("id", String.class);
        }
        return id;
    }

    /**
     * 从token中获取登录角色姓名
     */
    public String getUserNameFromToken(String token) {
        String name = null;
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            name = claims.get("name", String.class);
        }
        return name;
    }


    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     */
    public boolean validateToken(String token, String phone) {
        String phoneJwt = getPhoneFromToken(token);
        return phoneJwt.equals(phone) && !isTokenExpired(token);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }
}
